package com.ruoyi.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.wx.domain.TGoods;
import com.ruoyi.wx.domain.TGoodsCart;
import com.ruoyi.wx.domain.TOrder;
import com.ruoyi.wx.service.ITGoodsCartService;
import com.ruoyi.wx.service.ITGoodsService;
import com.ruoyi.wx.service.ITOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

/**
 * @Author: wind
 * @CreateTime: 2020-05-05
 * @Description: 订单接口
 */
@RestController
@RequestMapping("/api/order")
public class ApiTorderController {
    @Autowired
    private ITOrderService  orderService;
    @Autowired
    private ITGoodsService goodsService;
    @Autowired
    private ITGoodsCartService goodsCartService;

    @RequestMapping("/list")
    public AjaxResult orderList(TOrder order){
        String type = order.getType();
        if ( type.equals("2")){
            order.setOrderStatus("1");
        }else if (type.equals("3")){
            order.setOrderStatus("2");
        }
        return AjaxResult.success(orderService.list(new QueryWrapper<>(order)));
    }

    /**
     * 创建订单 并支付
     * */
    @RequestMapping("/pay")
    public AjaxResult createOrder(TOrder order){
        String str = getRandom(1,1000);
        String orderNo ="D"+ DateUtils.dateTime()+str;
        order.setOrderNo(orderNo);
        order.setOrderStatus("2");
        order.setCreateTime(new Date());
        order.setPayTime(new Date());
        String goodId = order.getGoodsId();
        // 删除购物车数量 更新商品数据
        TGoods goods= goodsService.getOne(new QueryWrapper<>(new TGoods().setGoodsId(goodId)));
        goods.setGoodsSales(goods.getGoodsSales()+1);
        goodsService.saveOrUpdate(goods);
        TGoodsCart goodsCart= goodsCartService.getOne(new QueryWrapper<>(new TGoodsCart().setGoodsId(goodId)));
        if(goodsCart !=null){
            if (goodsCart.getGoodsNum()>1){
                goodsCart.setGoodsNum(goodsCart.getGoodsNum()-1);
                goodsCartService.saveOrUpdate(goodsCart);
            }
            goodsCartService.removeById(goodsCart.getGoodsCartId());



        }

        return AjaxResult.success(orderService.save(order));
    }



    public static String getRandom(int min, int max){
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return String.valueOf(s);

    }

}
